package org.kommii.encryption;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;


public class AESHandler {
	
	private static final String ivspec = "0102030405060755";
	
	public static String encrypt(String strKey, String strIn) throws Exception {
        SecretKeySpec skeySpec = getKey(strKey);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivspec.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(strIn.getBytes());
        return Base64.encodeBase64String(encrypted);
//        return new BASE64Encoder().encode(encrypted);
    }

    public static String decrypt(String strKey, String strIn) throws Exception {
        SecretKeySpec skeySpec = getKey(strKey);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivspec.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted1 = Base64.decodeBase64(strIn);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original);
        return originalString;
    }

    private static SecretKeySpec getKey(String strKey) throws Exception {
        byte[] arrBTmp = strKey.getBytes();
        byte[] arrB = new byte[16]; // 创建一个空的16位字节数组(默认值为0)

        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }

        SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");

        return skeySpec;
    }
    
    public static String getIvspec() {
		return ivspec;
	}
    
    public static void main(String[] args) throws Exception {
       
        //String key = "9fb995c5-22f6-4c";
    	//String key = getKey("gfdgfg3dffgfgfgfge446547sdgdsfd4556").toString();
    	//System.out.println(key);
        String str = "sfdgeufdsuif4545efdsf555666";
        String s = encrypt("123456789",str);
        System.out.println(s);
        String ss = decrypt("123456789",s);
        System.out.println(ss);
        //codE = AESHandler.encrypt(key, Code);
       // codE = "SQJ6mlrssZfAds1swvNokg==";
        //System.out.println("原文:" + Code);
        //System.out.println("密钥:" + key);
       // System.out.println("密文:" + codE);
        //System.out.println("解密:" + AESHandler.decrypt(key, codE));
    }

	

}
